import { createStore } from 'vuex'
import { getBillListForRange } from '@/api/bill'
import { getClassList } from '@/api/class'
import iconList from '@/api/icon'
import { getBookList } from '@/api/book'
import { separateClass } from '@/utils/helper'

export default createStore({
  state: {
    billList: [],
    billTotal: {
      income: 0,
      pay: 0
    },
    payClassList: [{children: []}],
    incomeClassList: [{children: []}],
    classList: [{children: []}],
    iconList: [],
    bookList: [],
    isLogin: false,
    user: {},
    book: {},
    footerVisible: true
  },
  mutations: {
    get_clear_store: (state) => {
      state.billList = []
      state.billTotal = { income: 0, pay: 0 }
      state.payClassList = [{children: []}]
      state.incomeClassList = [{children: []}]
      state.classList = [{children: []}]
      state.iconList = []
      state.bookList = []
    },
    get_isLogin: (state, data) => {
      state.isLogin = data
    },
    get_book: (state, data) => {
      state.book = data
    },
    get_footer_visible: (state, data) => {
      state.footerVisible = data
    },
    get_bill_list: (state, data) => {
      state.billList = data.data
    },
    get_class_list: (state, data) => {
      state.classList = JSON.parse(JSON.stringify(data.data))
      state.payClassList = separateClass(data.data, 'pay')
      console.log(state.payClassList, 'pay');
      state.incomeClassList = separateClass(data.data, 'income')
      console.log(state.incomeClassList, 'income');
    },
    get_icon_list: (state, data) => {
      state.iconList = data.iconList
    },
    get_book_list: (state, data) => {
      state.bookList = data.data
    },
    get_total: (state, data) => {
      state.billTotal.income = data.data ? (data.data[0].income).toFixed(2) : 0.00
      state.billTotal.pay = data.data ? (data.data[0].pay).toFixed(2) : 0.00
    },
    get_user_info: (state, data) => {
      state.user = data
    }
  },
  actions: {
    fetchBillList:({ commit }, data) => {
      getBillListForRange(data).then((res) => {
        commit('get_bill_list', res)
      })
    },
    fetchBillTotal:({ commit }, data) => {
      getBillListForRange(data).then((res) => {
        commit('get_total', res)
      })
    },
    fetchClassList:({ commit }) => {
      getClassList().then((res) => {
        commit('get_class_list', res)
      })
    },
    fetchIconList:({ commit }) => {
      // getIconList().then((res) => {
        commit('get_icon_list', iconList)
      // })
    },
    fetchBookList:({ commit }) => {
      getBookList().then((res) => {
        commit('get_book_list', res)
      })
    }
  },
  modules: {
  }
})
